Highcharts.setOptions({ global: { useUTC: false } });
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
function formatterDate(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	var d = date.getDate();
	return y + '-' + m + '-' + d;
}
$(function(){
	// 添加easyui日期插件
	$('#start').datetimebox({
		formatter : function(date) {
			return date.Format("yyyy-MM-dd hh:mm:ss");
		}
	});
	$('#end').datetimebox({
		formatter : function(date) {
			return date.Format("yyyy-MM-dd hh:mm:ss");
		}
	});
	var d = new Date();
	d.setTime(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
	$('#start').datetimebox('setValue', d.Format("yyyy-MM-dd hh:mm:ss"));
	$('#end').datetimebox('setValue',new Date().Format("yyyy-MM-dd hh:mm:ss"));
	
	$(":radio").click(function(){
		d = new Date();
		if($(this).val() == 'day') {
			d.setTime(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
		}
		if($(this).val() == 'hour') {
			d.setTime(new Date().getTime() - 24 * 60 * 60 * 1000);
		}
		if($(this).val() == 'min') {
			d.setTime(new Date().getTime() - 60 * 60 * 1000);
		}
		$('#start').datetimebox('setValue', d.Format("yyyy-MM-dd hh:mm:ss"));
		$('#end').datetimebox('setValue',new Date().Format("yyyy-MM-dd hh:mm:ss"));
	 });
	// 设置日期只读
	$(".datebox :text").attr("readonly", "readonly");
	
	searchCapacity();
});

function createCapacityLineChart(obj,data,total){
	 new Highcharts.Chart({
      chart: {
          renderTo: obj,
          type: 'area'
      },
      title: {
          text: "",
          style: {
              fontSize:'13px'
          }
      },
      xAxis: {
    	  type:'datetime',
          labels: {  
 	         formatter: function () {  
 	             return new Date(this.value).Format("hh:mm");  
 	         }  
          }
      },
      yAxis: {
    	  title : {
    		  text : '总容量 '+total+' MB'
			}
      },
      tooltip: {
     	 pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b> ({point.y:,.0f} MB)<br/>',
     	 xDateFormat: '<b>日期:</b>%Y-%m-%d %H:%M:%S',
          shared: true
      },
      plotOptions: {
          area: {
              stacking: 'percent',
              lineColor: '#ffffff',
              lineWidth: 1,
              marker: {
                  lineWidth: 1,
                  lineColor: '#ffffff'
              }
          },
 	     series: {
 		   	  marker: {
 		             enabled: false
 		   	  }
 		 }
      },
      series:data
  });
};
function createCapacityLineChartForDay(obj,data,total){   
	 new Highcharts.Chart({
     chart: {
         renderTo: obj,
         type: 'area'
     },
     title: {
         text: "",
         style: {
             fontSize:'13px'
         }
     },
     xAxis: {
    	 type:'datetime',
         labels: {  
	         formatter: function () {  
	             return new Date(this.value).Format("MM-dd");  
	         }  
         }
     },
     yAxis: {
     	title : {
     		text : '总容量 '+total+' MB'
			}
     },
     tooltip: {
    	 pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b> ({point.y:,.0f} MB)<br/>',
    	 xDateFormat: '<b>日期:</b>%Y-%m-%d',
         shared: true
     },
     plotOptions: {
         area: {
             stacking: 'percent',
             lineColor: '#ffffff',
             lineWidth: 1,
             marker: {
                 lineWidth: 1,
                 lineColor: '#ffffff'
             }
         },
	     series: {
		   	  marker: {
		             enabled: false
		   	  }
		 }
     },
     series:data
 });
};
function createCapacityLineChartForHours(obj,data,total){    
	 new Highcharts.Chart({
     chart: {
         renderTo: obj,
         type: 'area'
     },
     title: {
         text: "",
         style: {
             fontSize:'13px'
         }
     },
     xAxis: {
         type:'datetime',
         labels: {  
	         formatter: function () {  
	             return new Date(this.value).Format("hh:mm");  
	         }  
         }
     },
     yAxis: {
    	 title : {
				text : '总容量 '+total+' MB'
			}
     },
     tooltip: {
    	 pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b> ({point.y:,.0f} MB)<br/>',
    	 xDateFormat: '<b>日期:</b>%Y-%m-%d %H:%M',
         shared: true
     }, 
     plotOptions: {
         area: {
             stacking: 'percent',
             lineColor: '#ffffff',
             lineWidth: 1,
             marker: {
                 lineWidth: 1,
                 lineColor: '#ffffff'
             }
         },
	     series: {
		   	  marker: {
		             enabled: false
		   	  }
		 }
     },
     series:data
 });
};
function strToDate(str) {
	 var tempStrs = str.split(" ");
	 var dateStrs = tempStrs[0].split("-");
	 var year = parseInt(dateStrs[0], 10);
	 var month = parseInt(dateStrs[1], 10) - 1;
	 var day = parseInt(dateStrs[2], 10);
	 var timeStrs = tempStrs[1].split(":");
	 var hour = parseInt(timeStrs [0], 10);
	 var minute = parseInt(timeStrs[1], 10) - 1;
	 var second = parseInt(timeStrs[2], 10);
	 var date = new Date(year, month, day, hour, minute, second);
	 return date;
}

function validateDay() {
	var sd = new Date(strToDate($('#start').datetimebox('getValue')));
	var ed = new Date(strToDate($('#end').datetimebox('getValue')));
	var stype = $('input:radio[name="searchType"]:checked').val();
	var resultStart = new Date(sd.getTime()).Format("yyyy-MM-dd hh:mm:ss");
	
	if(sd.getTime() > ed.getTime()) {
		$.messager.alert('提示:','起始时间不能大于结束时间！','info');
		return;
	}
	if(stype == 'day') {
		if((ed.getTime() - sd.getTime()) > 30 * 24 * 60 * 60 * 1000) {
			$.messager.alert('提示:','所选择时间段不能大于30天','info');
			return;
		}
	}
	if(stype == 'hour') {
		if((ed.getTime() - sd.getTime()) > 24 * 60 * 60 * 1000) {
			$.messager.alert('提示:','所选择时间段不能大于24小时','info');
			return;
		}
	}
	if(stype == 'min') {
		if((ed.getTime() - sd.getTime()) > 60 * 60 * 1000) {
			$.messager.alert('提示:','所选择时间段不能大于60分钟','info');
			return;
		}
	}
	var resultEnd = $('#end').datetimebox('getValue');
	return {searchType:stype,start:resultStart, end:resultEnd}
}
/**
 * 查询
 */
function searchCapacity(){
	 var result = validateDay();
	 $(".capacityLine").each(function(){
		 	var total = $(this).attr("valtotal");
		   	var toRender = $(this);
		       $.post(ctx + '/monitor/getCapacityLine',
		   		{ip:$(this).attr("val"),searchType:result.searchType,start:result.start,end:result.end},
		   		function(data){
		   			if(result.searchType == 'day') {
		   				createCapacityLineChartForDay(toRender[0],data,total);
		   			}
		   			if(result.searchType == 'hour') {
		   				createCapacityLineChartForHours(toRender[0],data,total);
		   			}
		   			if(result.searchType == 'min') {
		   				createCapacityLineChart(toRender[0],data,total);
		   			}
		   		});
		   });
}

